package indi.yuluo.controller;

import com.sun.deploy.net.HttpResponse;
import indi.yuluo.entity.user.UserInfo;
import indi.yuluo.service.UserService;
import indi.yuluo.util.UuidUtil;
import indi.yuluo.vo.Msg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @Author: yuluo
 * @CreateTime: 2022-08-14  09:48
 * @Description: TODO
 */

@RestController
@RequestMapping(value = "/common")
@Slf4j
@Api("用户头像文件上传相关类")
public class CommonController {

    @Resource
    private UserService userService;

    // 图片存储路径
    private static final String basePath = "E:\\Java\\Java_project\\XOJ\\ssm-plus\\ssm-plus\\src\\main\\webapp\\static\\userImg\\";

    /**
     * 上传文件控制器
     * @param
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation(value = "上传用户头像", httpMethod = "POST", notes = "上传文件")
    public Msg upload(@RequestParam("avatar") MultipartFile file, @RequestParam("token") String token) {

        // 接受图片和token信息
        // avatar

        log.info("avatar: {}, token: {}", file, token);

        /*
        当前的file是一个临时文件
        本次的文件上传结束之后，临时的文件就会被删除
        所以要存储到指定的目录中
         */

        // 获得原始文件名
        String originalFileName = file.getOriginalFilename();
        // 截取图片后缀名
        assert originalFileName != null;
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
        // 避免文件名重复 使用UUID命名文件
        String fileName = UuidUtil.getUuid() + suffix;

        // 如果没有目录，则创建一个目录
        File dir = new File(basePath);
        if (!dir.exists()) {
            // 创建目录
            dir.mkdirs();
        }

        try {
            /*
            将文件保存到本地文件夹中
            在配置文件中中动态配置存放的目录
             */
            file.transferTo(new File(basePath + fileName));
            // 将文件名保存到本地和token查出来的用户绑定到一起

            UserInfo userByToken = userService.getUserByToken(token);
            log.info("user {}", userByToken);
            userByToken.setAvatar(fileName);

            userService.saveUserAvatarAddress(userByToken);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return Msg.success().add("filename", fileName);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping(value = "/download")
    @ApiOperation(value = "用户头像下载", httpMethod = "GET", notes = "用于用户图像回显")
    public void download(String name, HttpServletResponse response) {

        // 通过输入流读取文件内容
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(basePath + name);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        // 通过输出流将文件写回到浏览器
        try {
            ServletOutputStream outputStream = response.getOutputStream();

            // 设置响应会回浏览器的数据类型为图片
            response.setContentType("image/jpeg");

            int length;
            byte[] bytes = new byte[1024];
            while (true) {
                assert fileInputStream != null;
                if ((length = fileInputStream.read(bytes)) == -1) break;
                // 写入到浏览器
                outputStream.write(bytes, 0, length);
                // 刷新流
                outputStream.flush();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
